import CommentApi, { CommentQueryRequest } from "@/api/articles/comment";
import { type PaginationProps } from "@/components/Table";
import { reactive, ref, onMounted, unref } from "vue";
import { useRouter } from "vue-router";
import dayjs from "dayjs";
export function useComment() {
  const form: CommentQueryRequest = reactive({
    articleId: 0,
    onlyVisible: false,
    isNeedAudit: false
  });
  const dataList = ref([]);
  const loading = ref(true);
  const pagination = ref<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const columns: TableColumnList = [
    {
      type: "selection",
      width: 55,
      align: "left",
      hide: ({ checkList }) => !checkList.includes("勾选列")
    },
    {
      label: "序号",
      type: "index",
      width: 70,
      hide: ({ checkList }) => !checkList.includes("序号列")
    },
    {
      label: "评论",
      prop: "content",
      minWidth: 200
    },
    {
      label: "评论人",
      prop: "userName",
      minWidth: 80
    },
    {
      label: "是否展示",
      prop: "visible",
      minWidth: 80,
      formatter: row => (row.visible ? "是" : "否")
    },
    {
      label: "是否需要审核",
      prop: "visible",
      minWidth: 80,
      formatter: row => (row.isNeedAudit ? "是" : "否")
    },
    {
      label: "发布时间",
      minWidth: 90,
      prop: "createTime",
      formatter: ({ createTime }) =>
        dayjs(createTime).format("YYYY-MM-DD HH:mm:ss")
    },
    {
      label: "操作",
      fixed: "right",
      width: 180,
      slot: "operation"
    }
  ];
  const router = useRouter();
  const goEditPath = postId => {
    router.push({ path: "/article/article/edit", query: { id: postId } });
  };
  async function onSearch() {
    loading.value = true;
    const data = await CommentApi.list(
      {
        page: unref(pagination).currentPage,
        limit: unref(pagination).pageSize
      },
      {
        ...form
      }
    );
    dataList.value = data.rows;
    unref(pagination).total = data.total;
    setTimeout(() => {
      loading.value = false;
    }, 500);
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };

  onMounted(() => {
    onSearch();
  });
  function handleSizeChange(_val: number) {
    onSearch();
  }

  function handleCurrentChange(_val: number) {
    onSearch();
  }
  return {
    form,
    loading,
    columns,
    dataList,
    pagination,
    goEditPath,
    onSearch,
    resetForm,
    handleSizeChange,
    handleCurrentChange
  };
}
